import pyautogui
import time
import win32com.client
import os
import pythoncom
import core.team_comm as team_comm

window_left = 0
window_wight = 0
window_top = 0
window_height = 0
game_window_left = 0
game_window_wight = 0
game_window_top = 0
game_window_height = 0


class IntoTeam:
    def __init__(self):
        pythoncom.CoInitialize()  # 初始化 COM
        self.ret_my_info = None
        self.dm = win32com.client.Dispatch("dm.dmsoft")
        print("大漠插件版本：", self.dm.Ver())
        script_dir = os.path.dirname(os.path.abspath(__file__))
        print("当前目录", script_dir)
        self.dm.SetPath(os.path.join(script_dir))

        # 关键修改1：强制设置绝对路径
        self.script_dir = os.path.dirname(os.path.abspath(__file__))
        self.dm.SetPath(self.script_dir)

        # 关键修改2：显式加载字库文件
        self.font_file = os.path.join(self.script_dir, "check_into_team.txt")
        if os.path.exists(self.font_file):
            # 3.1232版本必须用SetDict加载字库文件
            ret = self.dm.SetDict(0, self.font_file)
            print(f"字库加载状态: {'成功' if ret == 1 else '失败'}")
        else:
            with open(self.font_file, "w", encoding="gbk") as f:
                f.write("[game_font]\n")
            print("新建空字库文件")

    def __del__(self):
        if hasattr(self, 'dm'):
            self.dm = None  # 释放 COM 对象
        pythoncom.CoUninitialize()  # 反初始化 COM

    def find_game_window(self, partial_title):

        try:
            for i in range(100):
                # 获取所有包含部分标题的窗口
                windows = pyautogui.getWindowsWithTitle(partial_title)

                if windows:
                    print(f"找到 {len(windows)} 个匹配窗口:")
                    for i, win in enumerate(windows, 1):
                        print(f" 完整标题: '{win.title}'")

                    # 返回第一个匹配的窗口
                    return windows[0]
                else:
                    print(f"未找到标题包含 '{partial_title}' 的窗口，重试第'{i + 1}'次...")
                    time.sleep(1)

            print(f"未找到标题包含 '{partial_title}' 的窗口")
            return None
        except Exception as e:
            print(f"查找窗口时出错: {e}")
        return None

    def into_control(self):

        flag = self.into()
        if flag:
            t = team_comm.TeamCommander()
            t.set_ready_status()

        return flag

    def into(self):
        # 点击入队
        self.click_into()
        # 识别是否真实进队
        is_into = self.check_into_team()
        if is_into:
            return True
        else:
            for i in range(3):
                self.click_into()

        # 重试后再次确认
        retry_is_into = self.check_into_team()
        if  retry_is_into:
            return True
        else:
            return False

    def click_into(self):
        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            time.sleep(2)
            game_window.activate()
            time.sleep(0.5)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            # 点击进入队伍
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.80)),
                             y=(game_window_top + (game_window_height * 0.35)))

            time.sleep(1)
            for i in range(5):
                pyautogui.click()
                time.sleep(0.1)



    # 识别是否真实进队
    def check_into_team(self):

        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            time.sleep(2)
            game_window.activate()
            time.sleep(0.5)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            # 点击队伍二号位
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.2)),
                             y=(game_window_top + (game_window_height * 0.35)))
            time.sleep(0.5)
            pyautogui.click()

            return self.find_check_into_color( game_window_left, game_window_top, game_window_wight, game_window_height)
        return False

    def find_check_into_color(self, game_window_left, game_window_top, game_window_wight, game_window_height):

        x1 = (game_window_left + (game_window_wight * 0.095))
        y1 = (game_window_top + (game_window_height * 0.39))
        x2 = (game_window_left + (game_window_wight * 0.10))
        y2 = (game_window_top + (game_window_height * 0.41))

        self.dm.Capture(x1, y1, x2, y2,"check_into.bmp")

        color = "fdd92d-202020|a8a18c-202020|dac255-202020"
        # 3.1232版本OCR参数：区域坐标 + 颜色 + 相似度
        text = self.dm.Ocr(x1, y1, x2, y2, color, 0.8)
        if text and text == '已经进队':
            print(f"识别已经进队结果: {text}")
            return True
        else:
            print("识别已经进队失败！")
            return False


if __name__ == '__main__':
    i = IntoTeam()
    flag = i.check_into_team()
    print(flag)
